package com.dylan.历史.java8.并发增强;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Created by Dylan on 2018/7/30.
 */
public class Set视图 {

    public static void main(String[] args) {
        // 创建一个线程安全的Set,内部是ConcurrentHashMap,value是Boolean.TRUE
        ConcurrentHashMap.KeySetView<String, Boolean> set1 = ConcurrentHashMap.<String>newKeySet();
        set1.add("adsfas");
        System.out.println(set1);

        ConcurrentHashMap<String, Long> map = new ConcurrentHashMap<>(getWords().collect(Collectors.groupingBy(Function.<String>identity(), Collectors.counting())));

        // 从ConcurrentHashMap对象中获取Set,可以删除元素,但是不能添加元素
        Set<String> set2 = map.keySet();
        set2.remove("is"); // 删除后,map中响应的值也会删除
//        set2.add("sfdsf"); // UnsupportedOperationException,失败,因为无法向map中添加相应的值

        // 从ConcurrentHashMap对象中获取Set,并指定value的默认值,此时可以删除元素,也可以添加元素
        Set<String> set3 = map.keySet(1L);
        set3.add("aaaa");
    }

    private static Stream<String> getWords() {
        return Pattern.compile("[\\P{L}]+").splitAsStream("Ramesses VI was the fifth ruler of the Twentieth Dynasty of Egypt. He succeeded Ramesses V and reigned for about eight years in the mid-to-late 12th century BC before dying in his forties. Egypt lost control of its last strongholds in Canaan around the time of his reign. The pharaoh's power waned in Upper Egypt during his rule, while the high priest of Amun, Ramessesnakht, was turning Thebes in Upper Egypt into the religious capital and a second center of power on par with Pi-Ramesses in Lower Egypt, where the pharaoh resided. He was fond of cult statues of himself; more are known to portray him than any other Twentieth-Dynasty king after his father, Ramesses III. He usurped KV9, a tomb in the Valley of the Kings planned by and for Ramesses V, and had it enlarged and redecorated for himself. His mummy lay untouched for fewer than 20 years before pillagers damaged it.");
    }
}
